package com.b1502.store2.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.b1502.store2.R;
import com.b1502.store2.model.CartBean;
import com.b1502.store2.network.StoreParams;
import com.b1502.store2.util.UrlUtil;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.xutils.common.Callback;

import java.math.BigDecimal;


/**
 * 购物车界面
 * A simple {@link Fragment} subclass.
 * Use the {@link CartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CartFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private View view;
    private ListView cart_listView;
    private RelativeLayout cart_relativeLayout;
    private TextView cart_bigTextView;
    private CheckBox cart_image_selectAll;
    private Button cart_btn_settlement;
    private TextView cart_text_total;
    private static int count=0;
    private static double num=0;
    private CartBaseAdapter cartBaseAdapter;
    private CartBean[] bean;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };


    public CartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CartFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CartFragment newInstance(String param1, String param2) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_cart, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        getItems();
    }

    private void initView() {
        cart_listView = (ListView) view.findViewById(R.id.cart_listView);
        cart_relativeLayout = (RelativeLayout) view.findViewById(R.id.cart_RelativeLayout);
        cart_bigTextView = (TextView) view.findViewById(R.id.cart_bigTextView);
        cart_image_selectAll = (CheckBox) view.findViewById(R.id.cart_image_selectAll);
        cart_btn_settlement = (Button) view.findViewById(R.id.cart_btn_settlement);
        cart_text_total = (TextView) view.findViewById(R.id.cart_text_total);

    }

    private void getItems() {
        StoreParams params = new StoreParams(UrlUtil.GetItems);
        org.xutils.x.http().get(params, new Callback.CommonCallback<String>() {



            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                bean = gson.fromJson(result, CartBean[].class);


                if(bean.length!=0&& bean.length>0){
                    cart_bigTextView.setVisibility(View.GONE);
                    cart_relativeLayout.setVisibility(View.VISIBLE);
                    cart_listView.setVisibility(View.VISIBLE);
                }else {
                    cart_bigTextView.setVisibility(View.VISIBLE);
                    cart_relativeLayout.setVisibility(View.GONE);
                    cart_listView.setVisibility(View.GONE);
                }
//                Log.d(TAG, "哈哈哈"+bean[0].toString());
                cartBaseAdapter = new CartBaseAdapter();
                cart_listView.setAdapter(cartBaseAdapter);
                cart_image_selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if(cart_image_selectAll.isChecked()){
                            for (int i = 0; i < bean.length; i++) {
                                bean[i].setFlag(true);
                                cartBaseAdapter.notifyDataSetChanged();
                            }
                        }else {
                            for (int i = 0; i < bean.length; i++) {
                                bean[i].setFlag(false);
                                cartBaseAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    class CartBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
//        Log.i("TAGhahha", "getCount: "+list.length);
            return bean.length;
        }

        @Override
        public Object getItem(int position) {
            return bean[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder v;
            if (convertView == null) {
                convertView=View.inflate(getContext(), R.layout.cart_listview_item,null);
                v=new ViewHolder();
                v.select= (CheckBox) convertView.findViewById(R.id.cart_item_imageViewselect);
                v.googs= (ImageView) convertView.findViewById(R.id.cart_item_imageViewgood);
                v.name= (TextView) convertView.findViewById(R.id.cart_item_name);
                v.price= (TextView) convertView.findViewById(R.id.cart_item_price);
                v.num= (TextView) convertView.findViewById(R.id.cart_item_num);
                convertView.setTag(v);
            }else {
                v= (ViewHolder) convertView.getTag();
            }
            Monitor(v.select,position);
            v.select.setChecked(bean[position].isFlag());
            Glide.with(getContext()).load(UrlUtil.getImageUrl(bean[position].getImageUrl())).into(v.googs);
            v.name.setText(bean[position].getName());
            v.price.setText("￥"+bean[position].getPrice());
            v.num.setText("X"+bean[position].getCount()+"");
            return convertView;
        }

        public void Monitor(final CheckBox checkBox, final int position) {
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
                        if(isChecked){
                            CartBean bean1 = bean[position];
                            int sum = bean1.getCount();
                            double price1 = bean1.getPrice();
//                            Log.i(TAG, "onCheckedChanged: "+sum+"hahha"+price1);
                            num=(price1*sum)+num;
                            BigDecimal bg = new BigDecimal(num);
                            double f1 = bg.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                            cart_text_total.setText("总计:"+f1+"");
                            count =sum+count;
                            cart_btn_settlement.setText("结算("+count +")");
                        }else {
                            CartBean bean1 = bean[position];
                            int sum = bean1.getCount();
                            double price1 = bean1.getPrice();
                            num=(num-(price1*sum));
                            BigDecimal bg = new BigDecimal(num);
                            double f1 = bg.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                            cart_text_total.setText("总计:"+f1+"");
                            count=count-sum;
                            cart_btn_settlement.setText("结算("+count+")");
                        }


                }

            });


        }

        class ViewHolder{
            CheckBox select;
            ImageView googs;
            TextView name,price,num;
        }
    }


}
